﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Ninesky.Entities;
using Ninesky.InterfaceService;
using Ninesky.Service;
using Ninesky.WebAPI.Authorize;
using System.IO;

namespace Ninesky.WebAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public IConfiguration config { get; set; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options=> { options.Filters.Add(new NineskyAsyncAuthorizeAttribute()); });
            services.AddDbContext<NineskyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Ninesky.Entities")));
            services.AddTransient<InterfaceCategoryService, CategoryService>();
            config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).Add(new JsonConfigurationSource { Path = "authentication.json" }).Build();
            services.Configure<JwtConfig>(config.GetSection("JwtConfig"));
            services.AddCors(options=> options.AddPolicy("AllowDomain", builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials()));
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();
            app.UseMvc();
            app.UseCors("AllowDomain");
            
        }
    }
}
